package com.shijianchen.utils;

import com.shijianchen.projo.vos.SpTrees;
import com.shijianchen.utils.interfaces.TreeUtilsBuildInterface;

import java.util.*;

public class TreeUtils<E extends SpTrees,T extends SpTrees> {
    public TreeUtilsBuildInterface<E,T> treeUtilsBuild;
    public TreeUtils(TreeUtilsBuildInterface<E,T> treeUtilsBuild){
        this.treeUtilsBuild = treeUtilsBuild;
    }
    public List<TreeElement<T>> buildTree(List<E> list) throws IllegalAccessException {
        List<TreeElement<T>> arrays = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            E data = list.get(i);
            if(data.getParentId() == 0){/* 构建父级 */
                TreeElement<T> treeElement = treeUtilsBuild.updateTreeElement(data);
                treeElement.setParentId(data.getParentId());
                treeElement.setId(data.getId());
                treeElement.setChildren(new ArrayList<>());
                constructTree(treeElement,list);
                arrays.add(treeElement);
            }

        }
        return arrays;
    }
    private void constructTree(TreeElement<T> ele,List<E> list) throws IllegalAccessException {
        List<TreeElement<T>> children = ele.getChildren();
        for (int i = 0; i < list.size(); i++) {
            E data = list.get(i);
            if(data.getParentId()!=0){
                if (Objects.equals(ele.getId(), data.getParentId())){/* 如果*/
                    TreeElement<T> treeElement_child = treeUtilsBuild.updateTreeElement(data);
                    treeElement_child.setParentId(data.getParentId());
                    treeElement_child.setId(data.getId());
                    constructTree(treeElement_child,list);
                    children.add(treeElement_child);
                }
            }

        }
    }
}
